
var Content=React.createClass({
	getInitialState:function(){
		return {
			contentData:[]
		}
	},
	componentWillReceiveProps:function(props){
		var options=props.options,
			socialAccount=options.socialAccount,
			appId=socialAccount.app_id;

		if(appId!=this.appId){
			options.contentData(this,appId);
			this.appId=appId
		}
	},
	chartMap:[
		{
			title:'当前的关键数据',
			width:6,
			height:250,
			type:'index',
			row:1,
			getData:function(param,callback){
				setTimeout(function(){
					callback([{
						name:'用户总数',
						value:'150',
						icon:'user',
						className:'bg-aqua'
					},{
						name:'照片总数',
						value:'1500',
						icon:'image',
						className:'bg-green'
					}])
				},1000)
			},
			isLocked:true
		},
		{
			title:'男女比例',
			width:6,
			height:250,
			type:'pie',
			row:1,
			getData:function(param,callback){
				setTimeout(function(){
					callback([
						{
							"gender": "男",
							"value": 502
						},{
							"gender": "女",
							"value": 302
						},{
							"gender": "未知",
							"value": 200
						}
					])
				},1000)
			},
			isLocked:true
		},
		{
			title:'用户增长趋势图',
			width:12,
			height:300,
			type:'bar',
			datePick:true,
			row:2,
			getData:function(param,callback){
				setTimeout(function(){
					callback([ {
						"country": "2016-10-10",
						"visits": 2025
					}, {
						"country": "2016-10-11",
						"visits": 1882
					}, {
						"country": "2016-10-12",
						"visits": 1809
					}, {
						"country": "2016-10-13",
						"visits": 1322
					}, {
						"country": "2016-10-14",
						"visits": 1122
					}, {
						"country": "2016-10-15",
						"visits": 1114
					}, {
						"country": "2016-10-16",
						"visits": 984
					}, {
						"country": "2016-10-17",
						"visits": 1000
					}, {
						"country": "2016-10-18",
						"visits": 1100
					}, {
						"country": "2016-10-19",
						"visits": 1200
					}, {
						"country": "2016-10-20",
						"visits": 1400
					}, {
						"country": "2016-10-21",
						"visits": 1800
					}, {
						"country": "2016-10-22",
						"visits": 2600
					}])
				},1000)
			},
			isLocked:true
		},
		{
			title:'内容上传趋势图',
			width:12,
			height:300,
			type:'line',
			datePick:true,
			row:3,
			getData:function(param,callback){
				setTimeout(function(){
					callback([{
				        "key": "2012-07-27",
				        "value": 13
				    }, {
				        "key": "2012-07-28",
				        "value": 11
				    }, {
				        "key": "2012-07-29",
				        "value": 15
				    }, {
				        "key": "2012-07-30",
				        "value": 16
				    }, {
				        "key": "2012-07-31",
				        "value": 18
				    }, {
				        "key": "2012-08-01",
				        "value": 13
				    }, {
				        "key": "2012-08-02",
				        "value": 22
				    }, {
				        "key": "2012-08-03",
				        "value": 23
				    }, {
				        "key": "2012-08-04",
				        "value": 20
				    }, {
				        "key": "2012-08-05",
				        "value": 17
				    }, {
				        "key": "2012-08-06",
				        "value": 16
				    }, {
				        "key": "2012-08-07",
				        "value": 18
				    }, {
				        "key": "2012-08-08",
				        "value": 21
				    }])
				},1000)
			},
			isLocked:true
		},
		{
			title:'内容曝光趋势图',
			width:12,
			height:300,
			type:'line',
			datePick:true,
			row:4,
			getData:function(param,callback){
				setTimeout(function(){
					callback([{
				        "key": "2012-07-27",
				        "value": 1
				    }, {
				        "key": "2012-07-28",
				        "value": 7
				    }, {
				        "key": "2012-07-29",
				        "value": 15
				    }, {
				        "key": "2012-07-30",
				        "value": 4
				    }, {
				        "key": "2012-07-31",
				        "value": 12
				    }, {
				        "key": "2012-08-01",
				        "value": 11
				    }, {
				        "key": "2012-08-02",
				        "value": 9
				    }, {
				        "key": "2012-08-03",
				        "value": 5
				    }, {
				        "key": "2012-08-04",
				        "value": 6
				    }, {
				        "key": "2012-08-05",
				        "value": 7
				    }, {
				        "key": "2012-08-06",
				        "value": 3
				    }, {
				        "key": "2012-08-07",
				        "value": 9
				    }, {
				        "key": "2012-08-08",
				        "value": 14
				    }])
				},1000)
			},
			isLocked:true
		},
		{
			title:'社交行为趋势图',
			width:12,
			height:300,
			type:'stacked-bar',
			datePick:true,
			row:5,
			getData:function(param,callback){
				setTimeout(function(){
					callback([{
				        "key": '2016-10-01',
				        "分享到朋友圈": 3,
				        "分享给好友": 5,
				        "收藏": 2
				    }, {
				        "key": '2016-10-02',
				        "分享到朋友圈": 5,
				        "分享给好友": 9,
				        "收藏": 2
				    }, {
				        "key": '2016-10-03',
				        "分享到朋友圈": 7,
				        "分享给好友": 15,
				        "收藏": 5
				    }])
				},1000)
			},
			isLocked:true
		}
	],
	render:function(){
		var options=this.props.options,
			socialAccount=options.socialAccount,
			appId=socialAccount.app_id,
			contentData=this.state.contentData || [],
			rows=_.values(_.groupBy(this.chartMap,'row'));

		return (
			<div>
				<section className="content-header">
					<h1>
						跨屏朋友圈报表<small>{socialAccount.name}</small><a className="pull-right" href="/console">返回</a>
					</h1>
				</section>
				<div className="content">
					<div className="row">
		                <div className="col-md-12">
		                	{!appId?<Warning title="暂无报表可用" content="请先连接微信公众账号" />:''}
		                </div>
		            </div>
		            {rows.map(function(row,index){
	                	var height=_.max(_.pluck(row,'height'));

	                	return <div key={index} className="row">
	                		<div className="col-md-12">
		                		{row.map(function(chart,index2){
		                			chart.height=height;
		                			return <ReactReports key={index2} options={chart} />
		                		})}
		                	</div>
	                	</div>
	                })}
		        </div>
	        </div>
		)
	}
});

/*报表入口*/
var ReactReports = React.createClass({
	getInitialState:function(){
		return {
			data:null,
			startDate:moment().subtract(29, 'days').format('YYYY-MM-DD'),
			endDate: moment().format('YYYY-MM-DD'),
			isPending:false
		}
	},
	/*shouldComponentUpdate:function(nextProps,nextState){
		return JSON.stringify(nextState.data)!=JSON.stringify(this.state.data)
	},*/
	componentDidMount:function(){
		this.getData()
	},
	changeDate:function(start,end){
		var self=this,
			options=this.props.options,
			state=this.state;

		this.setState({
			startDate:start.format('YYYY-MM-DD'),
			endDate:end.format('YYYY-MM-DD')
		},function(){
			self.getData()
		})
	},
	getData:function(){
		var self=this,
			options=this.props.options,
			state=this.state;

		if(options.getData){
			this.setState({
				isPending:true
			},function(){
				options.getData(state,function(data){
					self.setState({
						data:data,
						isPending:false
					})
				})
			})
		}
	},
	render:function(){
		var options=this.props.options,
			data=this.state.data,
			isPending=this.state.isPending,
			getData=this.getData;

		return (
			<div className={"col-md-"+options.width}>
				<div className="box box-solid">
					<div className="box-header with-border">
						<h3 className="box-title" style={{fontSize:'16px'}}>{options.title}</h3>
						<div className="box-tools pull-right">
							{options.datePick?<ReactDatePick changeDate={this.changeDate} />:''}
						</div>
					</div>
					<div className="box-body">
						<div ref="legend"></div>
						<div className="chart" style={{height:options.height}}>
							{(function(){
								if(!isPending){
									if(data){
										switch (options.type){
											case 'index':
												return <IndexChart options={options} data={data} />;
											case 'pie':
												return <PieChart options={options} data={data} />;
											case 'bar':
												return <BarChart options={options} data={data} />;
											case 'stacked-bar':
												return <StackedBarChart options={options} data={data} />;
											case 'line':
												return <LineChart options={options} data={data} />
										}
									}else{
										return <ReLoad getData={getData} />
									}
								}else{
									return <Loading />
								}
							})()}
						</div>
					</div>
					{options.isLocked?<div className="overlay overlay-lock">
						<i className="fa fa-lock"></i>
					</div>:''}
				</div>
			</div>
		)
	}
});

var ReLoad = React.createClass({
	render:function(){
		return (
			<div className="overlay" onClick={this.props.getData}>
				<i className="fa fa-refresh" style={{marginLeft:'-76px',color:'#aaa',cursor:'pointer'}}> 重新加载</i>
			</div>
		)
	}
});

var Loading = React.createClass({
	render:function(){
		return (
			<div className="overlay">
				<i className="fa fa-refresh fa-spin"></i>
			</div>
		)
	}
});

/*指标展示*/
var IndexChart = React.createClass({
	render:function(){
		var options=this.props.options,
			data=this.props.data;

		return (
			<div className="indexchart-list">
				{data.map(function(i,index){
					return <div key={index} className="col-sm-6 indexchart-item">
						<div className={"small-box "+(i.className || 'bg-aqua')}>
							<div className="inner">
								<h3>{i.value || 0}</h3>
								<p>{i.name || '--'}</p>
							</div>
							<div className="icon">
								<i className={"fa fa-"+(i.icon || 'globe')}></i>
							</div>
						</div>
					</div>
				})}
			</div>
		)
	}
});

/*饼状图*/
var PieChart = React.createClass({
	componentDidMount:function(){
		this.componentDidUpdate()
	},
	componentDidUpdate:function(){
		var data=this.props.data;

		AmCharts.makeChart(this.refs.chart, {
			"type": "pie",
			"theme": "light",
			"dataProvider":data,
			"valueField": "value",
			"titleField": "gender",
			"pullOutRadius":0,
			"balloon":{
				"fixedPosition":true
			}
		});
	},
	render:function(){
		var options=this.props.options;

		return (
			<div ref="chart" style={{height:options.height}}></div>
		)
	}
});

/*柱状图*/
var BarChart = React.createClass({
	componentDidMount:function(){
		this.componentDidUpdate()
	},
	componentDidUpdate:function(){
		var data=this.props.data;

		AmCharts.makeChart(this.refs.chart, {
		  "type": "serial",
		  "theme": "light",
		  "dataProvider":data,
		  "valueAxes": [ {
		    "gridColor": "#FFFFFF",
		    "gridAlpha": 0.2,
		    "dashLength": 0
		  } ],
		  "gridAboveGraphs": true,
		  "startDuration": 1,
		  "graphs": [{
		    "balloonText": "[[category]]: <b>[[value]]</b>",
		    "fillAlphas": 0.8,
		    "lineAlpha": 0.2,
		    "type": "column",
		    "valueField": "visits"
		  }],
		  "chartCursor": {
		    "categoryBalloonEnabled": false,
		    "cursorAlpha": 0,
		    "zoomable": false
		  },
		  "categoryField": "country",
		  "categoryAxis": {
		    "gridPosition": "start",
		    "gridAlpha": 0,
		    "tickPosition": "start",
		    "tickLength": 20
		  }

		} );
	},
	render:function(){
		var options=this.props.options;

		return (
			<div ref="chart" style={{height:options.height}}></div>
		)
	}
});

/*柱状堆积图*/
var StackedBarChart = React.createClass({
	componentDidMount:function(){
		this.componentDidUpdate()
	},
	componentDidUpdate:function(){
		var data=this.props.data;

		AmCharts.makeChart(this.refs.chart, {
			"type": "serial",
			"theme": "light",
			"legend": {
				"horizontalGap": 10,
				"maxColumns": 1,
				"position": "right",
				"useGraphSettings": true,
				"markerSize": 10
			},
			"dataProvider":data,
			"valueAxes": [{
		        "stackType": "regular",
		        "axisAlpha": 0.3,
		        "gridAlpha": 0
		    }],
			"graphs":_.rest(_.keys(data[0])).map(function(i){
				return {
			        "balloonText": "<b>[[title]]</b><br><span style='font-size:14px'>[[category]]: <b>[[value]]</b></span>",
			        "fillAlphas": 0.8,
			        "labelText": "[[value]]",
			        "lineAlpha": 0.3,
			        "title": i,
			        "type": "column",
					"color": "#000000",
			        "valueField": i
			    }
			}),
			"categoryField": "key",
		    "categoryAxis": {
		        "gridPosition": "start",
		        "axisAlpha": 0,
		        "gridAlpha": 0,
		        "position": "left"
		    }
		} );
	},
	render:function(){
		var options=this.props.options;

		return (
			<div ref="chart" style={{height:options.height}}></div>
		)
	}
});

/*折线图*/
var LineChart = React.createClass({
	componentDidMount:function(){
		this.componentDidUpdate()
	},
	componentDidUpdate:function(){
		var data=this.props.data;

		AmCharts.makeChart(this.refs.chart, {
		    "type": "serial",
		    "theme": "light",
		    "marginLeft": 40,
		    "autoMarginOffset": 20,
		    "valueAxes": [{
		        "id": "v1",
		        "axisAlpha": 0,
		        "position": "left",
		        "ignoreAxisWidth":true
		    }],
		    "graphs": [{
		        "balloon":{
		          "drop":true,
		          "adjustBorderColor":false,
		          "color":"#ffffff"
		        },
		        "bullet": "round",
		        "bulletBorderAlpha": 1,
		        "bulletColor": "#FFFFFF",
		        "bulletSize": 5,
		        "hideBulletsCount": 50,
		        "lineThickness": 2,
		        "title": "red line",
		        "useLineColorForBulletBorder": true,
		        "valueField": "value",
		        "balloonText": "<span style='font-size:18px;'>[[value]]</span>"
		    }],
		    "chartCursor": {
		        "pan": true,
		        "valueLineEnabled": true,
		        "valueLineBalloonEnabled": true,
		        "cursorAlpha":1,
		        "cursorColor":"#258cbb",
		        "limitToGraph":"g1",
		        "valueLineAlpha":0.2,
		        "valueZoomable":true
		    },
		    "categoryField": "key",
		    "dataProvider":data
		});
	},
	render:function(){
		var options=this.props.options;

		return (
			<div ref="chart" style={{height:options.height}}></div>
		)
	}
});

/*时间选择器-完全版*/
var ReactDatePick=React.createClass({
	componentDidMount:function(){
		var self=this,
			changeDate=this.props.changeDate;
		$(this.refs.daterangeBtn).daterangepicker(
			{
			  ranges: {
				'今天': [moment(), moment()],
				'昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
				'最近7天': [moment().subtract(6, 'days'), moment()],
				'最近30天': [moment().subtract(29, 'days'), moment()],
				'本月': [moment().startOf('month'), moment().endOf('month')],
				'上月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
			  },
			  startDate: moment().subtract(29, 'days'),
			  endDate: moment(),
			  maxDate:new Date()
			},
			function (start,end,name) {
				if(name=='任意范围'){
					self.refs.reportrange.innerHTML=start.format('YYYY-MM-DD') + ' - ' + end.format('YYYY-MM-DD')	
				}else{
					self.refs.reportrange.innerHTML=name
				}
				changeDate(start,end)
			}
		)
	},
	render:function(){
		var dir=this.props.dir||'right',
			warpClass='btn-group pull-'+dir;

		return (
			<div className={warpClass} style={dir=='left'?{}:{'marginLeft':'10px'}}>
				<button type="button" className="btn btn-default pull-right btn-sm" ref="daterangeBtn" style={{fontSize:'12px'}}>
					<i className="fa fa-calendar"></i>
					<span ref="reportrange" style={{margin:'0 10px'}}>最近30天</span>
					<i className="fa fa-caret-down"></i>
				</button>
			</div>
		)	
	}
});

var WallCard=React.createClass({
	render:function(){
		var data=this.props.data;

		return (
			<div className="wall_item col-lg-3 col-md-4 col-sm-6 col-xs-12">
				<div className="box box-solid" style={data.background_color?{backgroundColor:unescape(data.background_color)}:{backgroundImage:'url('+data.background+')'}}>
					<div className="box-header">
						<h4>{data.logo?<img src={data.logo} />:''}<a href={"/wall/"+data.id} target="_blank">{data.name}</a></h4>
					</div>
					<div className="box-body" style={{color:unescape(data.font_color)}}>
						<p>{data.description || '暂无描述'}</p>
						<p className="box-date">最后更新：{data.date || '--'}</p>
						<div className="clearfix"></div>
						<a href={"/walls/" + data.id + "/edit"} className="box-setting pull-right" title="设置朋友圈"><i className="fa fa-gear"></i></a>
						<a href={"/walls/" + data.id + "/reports"} className="box-setting pull-right" title="查看报表"><i className="fa fa-bar-chart"></i></a>
					</div>
					<div className="box-footer with-border">
						<a href={"/walls/"+data.id+"/fans"} className="btn btn-flat btn-default">用户列表<strong> ({data.user_count || '--'})</strong></a>
						<a href={"/walls/"+data.id+"/photo"} className="btn btn-flat btn-primary">全部照片<strong> ({data.photo_count || '--'})</strong></a>
					</div>
				</div>
			</div>
		)
	}
});

var Warning=React.createClass({
	render:function(){
		var title=this.props.title,
			content=this.props.content;

		return (
			<div className="callout callout-warning">
				<h4>{title}</h4>
				<p>{content}</p>
			</div>
		)
	}
});


